import { login, logout, getMenus } from '@/api/user'
import { getToken, setToken, removeToken, setUserInfo, getUserInfo } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: getUserInfo()
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ type: 1, account: username.trim(), password: password }).then(data => {
        commit('SET_TOKEN', data.token)
        commit('SET_USERINFO', data.user_info)
        setToken(data.token)
        setUserInfo(data.user_info)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  getMenu({ commit }) {
    return getMenus().then(data => {
      return data
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

